package com.crrc.yzt.demo.activity

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.crrc.yzt.demo.blue.R
import com.crrc.yzt.demo.base.BaseActivity
import com.crrc.yzt.demo.blue.databinding.ActivityCarListBinding
import com.crrc.yzt.demo.blue.databinding.ItemCarBinding
import com.crrc.yzt.demo.model.ItemMain
import com.crrc.yzt.demo.vm.MainVM
import kotlinx.coroutines.launch

class CarListActivity : BaseActivity() {

    private lateinit var binding: ActivityCarListBinding

    private val viewModel by viewModels<MainVM> ()

    private var myAdapter: MyAdapter? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarBackground(R.color.colorPrimary)
        binding = ActivityCarListBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        initObserver()
        loadData()
    }

    private fun loadData() {
        viewModel.loadList()
    }


    private fun initObserver() {
        lifecycleScope.launch {
            viewModel.itemMainStateFlow.collect{
                myAdapter?.apply {
                    clear()
                    setData(it)
                    notifyDataSetChanged()
                }
            }
        }
    }


    private fun initView() {

        binding.apply {

            myAdapter = MyAdapter {
                startActivity(Intent(mActivity, CarHomeActivity::class.java).apply {
                })
            }
            recyclerView.adapter = myAdapter

        }

    }


}



private class MyAdapter(val itemClick:(item: ItemMain)->Unit): RecyclerView.Adapter<CarViewHolder>(){

    private val data = mutableListOf<ItemMain>()

    fun setData(list: List<ItemMain>?){
        if (list != null) {
            data.addAll(list)
        }
    }

    fun clear(){
        data.clear()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {
        val binding = ItemCarBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return CarViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: CarViewHolder, position: Int) {

        val item = data[position]

        holder.binding.root.setOnClickListener {
            itemClick.invoke(item)
        }
        holder.binding.carInfo = data[position].item1
    }

}


private class CarViewHolder(val binding: ItemCarBinding) : RecyclerView.ViewHolder(binding.root){

}